import React, { useState, useEffect } from 'react';
import { SearchOutlined } from '@ant-design/icons';
import { DOCNAME, ip, port } from '../constants/index';
import { Input, Button, Space, Table, Tag, Drawer, Radio } from 'antd';
import { BlockOutlined } from '@ant-design/icons';
import { Query } from '../../gis/utils/Query';
import { createDraw } from '../../gis/utils/Draw';
import '../assets/css/popUp.css';
const MapSearch = ({ map }) => {
  const [visible, setVisible] = useState(false);
  const [data, setDate] = useState([]);
  const [item, setItem] = useState({
    事件等级: '4',
    事件类型: '碰撞',
    发生地点: '新中地',
  });
  const { Search } = Input;
  //搜索
  const onSearch = (value) => {
    let name = value.split('').join('%');
    let where = `事件类型 like '%${name}%'`;
    const service = { docName: DOCNAME, layerId: 2 };
    Query.queryBySql({
      where,
      service,
      callback: querySuccess,
    });
  };
  let source = new ol.source.Vector({
    wrapX: false,
  });
  let searchLayer = new ol.layer.Vector({
    title: 'heidian',
    source,
    style: new ol.style.Style({
      image: new ol.style.Circle({
        radius: 10,
        fill: new ol.style.Fill({
          color: '#3771D9',
        }),
      }),
    }),
  });
  //popup
  //popoup
  let popup;
  //拉框
  /* 激活画笔实现拉框Box */
  let boxsource = new ol.source.Vector({
    wrapX: false,
  });
  let boxLayer = new ol.layer.Vector({
    source: boxsource,
  });
  // 判断是否map被初始化
  const [hasPassMap, setHasPassMap] = useState(false);
  useEffect(() => {
    if (map == undefined) {
      setHasPassMap(true);
    }
    if (map) {
      map.addLayer(searchLayer);
      map.addLayer(boxLayer);
      /* 2、将DOM转化成overlay */
      var container = document.getElementById('popup');
      var content = document.getElementById('popup-content');
      var closer = document.getElementById('popup-closer');
      popup = new ol.Overlay({
        //要转换成overlay的HTML元素
        element: container,
        //当前窗口可见
        autoPan: true,
        //Popup放置的位置
        positioning: 'bottom-center',
        //是否应该停止事件传播到地图窗口
        stopEvent: true,
        autoPanAnimation: {
          //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度
          duration: 250,
        },
      });
      map.addOverlay(popup);
      //添加关闭按钮的单击事件（隐藏popup）
      closer.onclick = function () {
        //未定义popup位置
        popup.setPosition(undefined);
        //失去焦点
        closer.blur();
        return false;
      };
    }
  }, [hasPassMap]);

  const querySuccess = (result) => {
    source.clear();
    var format = new Zondy.Format.PolygonJSON();
    //将MapGIS要素JSON反序列化为ol.Feature类型数组
    var features = format.read(result);
    source.addFeatures(features);

    map.on('click', function (e) {
      // 获取当前点击的点是否存在要素, 并返回
      const feature = map.forEachFeatureAtPixel(
        //
        e.pixel,
        function (feature, layer) {
          setItem(feature.values_.values_);
          return feature;
        }
      );
      if (feature) {
        if (popup.getPosition() == undefined) {
          var position = feature.getGeometry().flatCoordinates;
          popup.setPosition(position);
        }
      }
    });
    //为map添加鼠标移动事件监听，当指向标注时改变鼠标光标状态
    map.on('pointermove', function (e) {
      var pixel = map.getEventPixel(e.originalEvent);
      var hit = map.hasFeatureAtPixel(pixel);
      map.getTargetElement().style.cursor = hit ? 'pointer' : '';
    });
  };

  let draw = null;
  const DrawActive = () => {
    draw = createDraw({
      type: 'Box',
      source: boxsource,
      callback: handleDraw,
    });
    map.addInteraction(draw);
  };
  const handleDraw = (e) => {
    boxsource.clear();
    const geom = e.feature.getGeometry();

    const service = { docName: DOCNAME, layerId: 2 };
    Query.queryByGeom({
      geom,
      service,
      callback: querySuccess2,
    });
  };
  const [columns, setColumns] = useState();
  const querySuccess2 = (result) => {
    //初始化Zondy.Format.PolygonJSON类
    var format = new Zondy.Format.PolygonJSON();
    //将MapGIS要素JSON反序列化为ol.Feature类型数组
    var features = format.read(result);
    const featureData = features.map((item) => {
      return { FID: item.id_, ...item.values_.values_ };
    });
    let dataIndex = Object.keys(featureData[0]);
    setColumns(
      dataIndex.map((item) => {
        return { title: item, dataIndex: item, key: item };
      })
    );

    setDate(featureData);
    setVisible(true);
  };

  const showDrawer = () => {
    setVisible(true);
  };
  const onClose = () => {
    setVisible(false);
  };
  return (
    <div>
      <Search
        placeholder="input search text"
        onSearch={onSearch}
        style={{
          width: 300,
          position: 'absolute',
          top: '80px',
          left: '200px',
          zIndex: '200',
          display: 'inline-block',
        }}
      />
      <Button
        onClick={DrawActive}
        style={{
          position: 'absolute',
          top: '80px',
          left: '500px',
          zIndex: '200',
          display: 'inline-block',
        }}
        type="primary"
        shape="circle"
        icon={<SearchOutlined />}
      />

      <Drawer
        title="事件查询"
        placement="bottom"
        closable={true}
        onClose={onClose}
        visible={visible}
        key="bottom"
      >
        <Table columns={columns} dataSource={data} />
      </Drawer>
      <div id="popup" className="ol-popup">
        <a href="#" id="popup-closer" className="ol-popup-closer"></a>
        <div id="popup-content">
          <p>事件类型：{item.事件类型}</p>
          <p>事件等级：{item.事件等级}</p>
          <p>发生地点：{item.发生地点}</p>
        </div>
      </div>
    </div>
  );
};

export default MapSearch;
